package org.zjut.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.zjut.db.AttributeDataBase;
import org.zjut.util.CommonUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/**
 *  @date 2017/8/13
 *  @author Rising
 *  @des 属性操作controller
 */
@Controller
public class AttributeController {
    @Autowired
    AttributeDataBase attributeDataBase;

    /**
     * 添加属性
     * @param request
     * @return
     */
    @RequestMapping(value = "/addAttribute", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String addAttribute(HttpServletRequest request){
        JSONObject params = JSON.parseObject(CommonUtil.getBodyRequest(request));
        if(request==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }
        return JSON.toJSONString(attributeDataBase.addAttribute(params));
    }

    /**
     * 修改属性
     * @param request
     * @return
     */
    @RequestMapping(value = "/editAttribute", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String editAttribute(HttpServletRequest request){
        JSONObject params = JSON.parseObject(CommonUtil.getBodyRequest(request));
        System.out.println(params);
        if(request==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }
        return JSON.toJSONString(attributeDataBase.editAttribute(params));
    }

    /**
     * 删除属性
     * @return
     */
    @RequestMapping(value = "/delAttribute/{attrCode}", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String delAttribute(@PathVariable String attrCode){
        if(attrCode==null){
            return JSON.toJSONString(CommonUtil.setErrorInfo("请求参数有问题，请注意检查"));
        }
        return JSON.toJSONString(attributeDataBase.delAttribute(attrCode));
    }


    /**
     * 查询属性
     * @param request
     * @return
     */
    @RequestMapping(value = "/getAttribute", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getAttribute(HttpServletRequest request){
        if(request==null){
            return JSON.toJSONString(attributeDataBase.getAtrribute(new HashMap<String, Object>()));
        }
        JSONObject params = JSON.parseObject(CommonUtil.getBodyRequest(request));
        return JSON.toJSONString(attributeDataBase.getAtrribute(params));
    }

}
